package com.ruoyi.quartz.uniController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.enumutil.AddGroupEnum;
import com.ruoyi.system.enumutil.AddWechatEnum;
import com.ruoyi.system.enumutil.AdvertisementEnum;
import com.ruoyi.system.mapper.GroupImgMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import org.apache.commons.math3.analysis.function.Add;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;

/*
 *  @author 雨安
 *  类名： GroupCodeController
 *  创建时间：2025/2/13
 *  微信群聊
 */
@RestController
@RequestMapping("/uni/group/code")
public class GroupCodeController {

    //群聊信息
    @Resource
    private AddGroupService addGroupService;

    //广告信息
    @Resource
    private AdvertisementService advertisementService;

    //群聊名称分组
    @Resource
    private GroupNameService groupNameService;

    //添加微信好友
    @Resource
    private AddWechatService addWechatService;

    //用户
    @Resource
    private SysUserMapper sysUserMapper;

    //冻结表
    @Resource
    private FreezeService freezeService;

    //获取token
    public static String getAccessToken() throws Exception {
        String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbd664677f8367061&secret=b498ec52efbacda9913b7e717371a7fc";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 打印返回的完整响应
//        System.out.println("Response: " + response.toString());
        // 解析 JSON，提取 access_token
        JSONObject jsonResponse = new JSONObject(response.toString());
        String accessToken = jsonResponse.getString("access_token");
        // 返回 access_token
        return accessToken;
    }



    //文字判断
    private static String sendMsgSecurityCheckRequest(String accessToken, String content) {
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头（如果需要的话，这里可以添加更多的请求头）
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

        System.out.println(content);
        // 创建请求体
        String jsonRequest = "{\"content\":\"" + content + "\"}";
        StringEntity entity = new StringEntity(jsonRequest, "UTF-8");
        httpPost.setEntity(entity);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(responseBody + "我的拦截结果");
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    @Resource
    private GroupImgMapper groupImgMapper;


    //发布群聊
    @PostMapping("/add/group")
    public AjaxResult addGroup(@RequestBody AddGroup addGroup) throws Exception {
        //判断名称
        if (StringUtils.isBlank(addGroup.getGroupName())){
            //返回提示
            return AjaxResult.error("请输入群名称。");
        }
        //判断群人数
        if (Objects.isNull(addGroup.getGroupPersonCount()) || addGroup.getGroupPersonCount() <=0 || addGroup.getGroupPersonCount() >200){
            //返回提示
            return AjaxResult.error("群人数小于0或大于200无法发布。");
        }
        //判断群类型
        if (Objects.isNull(addGroup.getGroupId())){
            //返回提示
            return AjaxResult.error("请选择群类型");
        }
        //判断群二维码
        if (StringUtils.isBlank(addGroup.getQrCode())) {
            //返回提示
            return AjaxResult.error("请上传群二维码");
        }
        /********************微信审核****************************************/
        String accessToken = getAccessToken(); // 替换为你的 access_token
        //获取响应
        String responseStr = sendMsgSecurityCheckRequest(accessToken, addGroup.getGroupName());
        //解析数据
        JsonObject jsonResponse = JsonParser.parseString(responseStr).getAsJsonObject();
        //获取响应码
        int errcode = jsonResponse.get("errcode").getAsInt();
        //判断响应码
        if (errcode == 87014){
            //返回结果
            return AjaxResult.error("发布的内容不合法。");
        }
        /*******************微信审核******************************************/
        System.out.println(addGroup);
        //查询用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //判断用户不为 null
        if (Objects.nonNull(sysUser) && Objects.nonNull(sysUser.getMemberEndTime()) && sysUser.getMemberEndTime().after(new Date())){

            int randomNumber = (int)(Math.random() * 30 ) + 1; // 生成 1 到 10 的随机整数

            GroupImg groupImg = groupImgMapper.selectOne(new LambdaQueryWrapper<GroupImg>()
                    .last("limit " + randomNumber + ",1")
            );
            //设置群头像
            addGroup.setGroupImg(groupImg.getImageUrl());
            //设置状态
            addGroup.setStatus(AddGroupEnum.ShenHeTongGuo.getStatus());
            //设置用户编号
            addGroup.setUserId(SecurityUtils.getUserId());
            //设置默认值
            addGroup.setCreateTime(new Date());
            addGroup.setCreateBy(SecurityUtils.getUsername());
            addGroup.setUpdateTime(new Date());
            addGroup.setUpdateBy(SecurityUtils.getUsername());
            addGroup.setDeleteFlag(Boolean.FALSE);
            //执行添加
            addGroupService.save(addGroup);
            //返回结果
            return AjaxResult.success("发布成功");
        }else{
            //返回结果
            return AjaxResult.success("您还不是本平台高级会员,请开通会员后使用该功能。");
        }
    }

//    //发布好友
//    @PostMapping("/add/wechat")
//    public AjaxResult addWechat(@RequestBody AddWechat addWechat){
//        System.out.println(addWechat);
//        //查询登录用户
//        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
//        //得到结果
//        BigDecimal needFunds = BigDecimal.valueOf(addWechat.getNeedCount() * 1.5);
//        //相减判断用户是否余额足够
//        BigDecimal subtract = sysUser.getScore().subtract(needFunds);
//        //打印需要金额查看
//        System.out.println(needFunds + "==================" + subtract);
//        //判断是否足够
//        if (subtract.compareTo(BigDecimal.ZERO) < 0){
//            return AjaxResult.success("用户余额不足,请充值积分。");
//        }
//        //设置用户余额
//        sysUser.setScore(subtract);
//        //设置默认值
//        sysUser.setUpdateBy(SecurityUtils.getUsername());
//        sysUser.setUpdateTime(new Date());
//        //执行修改 此操作扣费
//        sysUserMapper.updateUser(sysUser);
//        System.out.println(222222);
//        System.out.println(SecurityUtils.getUsername());
//        System.out.println(SecurityUtils.getLoginUser().getUser().getAvatar());
//        //设置微信昵称
//        addWechat.setWechatName(SecurityUtils.getLoginUser().getUser().getNickName());
//        //设置微信头像
//        addWechat.setWechatImg(SecurityUtils.getLoginUser().getUser().getAvatar());
//        //设置影响力
//        addWechat.setInfluence(0);
//        //设置用户编号
//        addWechat.setUserId(SecurityUtils.getUserId());
//        //设置状态
//        addWechat.setStatus(AddWechatEnum.ShenHeTongGuo.getStatus());
//        //设置默认值
//        addWechat.setCreateBy(SecurityUtils.getUsername());
//        addWechat.setCreateTime(new Date());
//        addWechat.setUpdateBy(SecurityUtils.getUsername());
//        addWechat.setUpdateTime(new Date());
//        addWechat.setDeleteFlag(Boolean.FALSE);
//        //执行添加
//        addWechatService.save(addWechat);
//        //添加冻结表
//        Freeze freeze = new Freeze();
//        //设置冻结资金
//        freeze.setFreezeFund(needFunds);
//        //设置冻结的用户编号
//        freeze.setUserId(SecurityUtils.getUserId());
//        //设置任务id
//        freeze.setAddId(addWechat.getId());
//        //冻结原因
//        freeze.setFreezeReason("用户发布了好友添加任务。");
//        //设置默认值
//        freeze.setCreateBy(SecurityUtils.getUsername());
//        freeze.setCreateTime(new Date());
//        freeze.setUpdateBy(SecurityUtils.getUsername());
//        freeze.setUpdateTime(new Date());
//        freeze.setDeleteFlag(Boolean.FALSE);
//        //执行添加
//        freezeService.save(freeze);
//
//        //返回结果
//        return AjaxResult.success();
//    }



    //查询轮播图
    @PostMapping("/get/advertisement")
    public AjaxResult getAdvertisement(){
       List<Advertisement> li =advertisementService.list(new LambdaQueryWrapper<Advertisement>()
                //审核状态
                .eq(Advertisement::getStatus, AdvertisementEnum.ShenHeTongGuo.getStatus())
                //逻辑删除为false
                .eq(Advertisement::getDeleteFlag,Boolean.FALSE)
        );
        System.out.println(9090);
        System.out.println(li);
        //返回结果
        return AjaxResult.success(advertisementService.list(new LambdaQueryWrapper<Advertisement>()
                //审核状态
                .eq(Advertisement::getStatus, AdvertisementEnum.ShenHeTongGuo.getStatus())
                //逻辑删除为false
                .eq(Advertisement::getDeleteFlag,Boolean.FALSE)
        ));
    }

    //查询微信群名称分组  此处不用分页！！！ 20250217代码朱思恒,因为mp分页器没注册好,刚刚好这里需要全部查询
    @PostMapping("/get/group/name")
    public AjaxResult getGroupName(@RequestBody GroupName groupName){
        //创建分页对象
        Page<GroupName> page = new Page<>();
        //设置页码
        page.setCurrent(groupName.getCurrent());
        //设置行数
        page.setSize(groupName.getSize());
        //查询数据
        groupNameService.page(page,new LambdaQueryWrapper<GroupName>()
                //逻辑删除为false
                .eq(GroupName::getDeleteFlag,Boolean.FALSE)
                //排序
                .orderByDesc(GroupName::getCreateTime)
        );
        //设置总行数
        page.setTotal(groupNameService.count(new LambdaQueryWrapper<GroupName>()
                //逻辑删除为false
                .eq(GroupName::getDeleteFlag,Boolean.FALSE)
        ));
        //返回结果
        return AjaxResult.success(page);
    }

    //查询微信加群
    @PostMapping("/get/add/group")
    public AjaxResult getAddWechat(@RequestBody AddGroup addGroup){
        System.out.println(addGroup + "我是测试sss");
        //创建分页对象
        Page<AddGroup> page = new Page<>();
        //设置页码
        page.setCurrent(addGroup.getCurrent());
        //设置行数
        page.setSize(addGroup.getSize());
        //查询数据
        addGroupService.page(page,new LambdaQueryWrapper<AddGroup>()
                //群分组
                .eq(Objects.nonNull(addGroup.getGroupId()),AddGroup::getGroupId,addGroup.getGroupId())
                //审核通过
                .eq(AddGroup::getStatus, AddGroupEnum.ShenHeTongGuo.getStatus())
                //逻辑删除
                .eq(AddGroup::getDeleteFlag,Boolean.FALSE)
                //置顶时间
                .orderByDesc(AddGroup::getTopTime)
                //创建时间
                .orderByDesc(AddGroup::getTopEndTime)
                //添加分页语句
                .last(" limit " + (addGroup.getCurrent() - 1) * addGroup.getSize() +"," + addGroup.getSize())
        );
        //设置总行数
        page.setTotal(addGroupService.count(new LambdaQueryWrapper<AddGroup>()
                //群分组
                .eq(Objects.nonNull(addGroup.getGroupId()),AddGroup::getGroupId,addGroup.getGroupId())
                //审核通过
                .eq(AddGroup::getStatus, AddGroupEnum.ShenHeTongGuo.getStatus())
                //逻辑删除
                .eq(AddGroup::getDeleteFlag,Boolean.FALSE)
        ));
        //遍历数据
        page.getRecords().forEach(ele->{
            Date createTime = ele.getCreateTime(); // 替换为实际获取时间的方式
            if (Objects.nonNull(createTime)) {
                long currentTimeMillis = System.currentTimeMillis();
                // 将 createTime 转换为毫秒数
                long createTimeMillis = createTime.getTime(); // 直接使用 getTime() 获取毫秒数
                // 计算时间差（以分钟为单位）
                long minutes = (currentTimeMillis - createTimeMillis) / (1000 * 60);
                if (minutes > 720){
                    ele.setFrontTime("1天前");
                }else{
                    ele.setFrontTime(String.valueOf(minutes) + "分钟前");
                }

            }
        });
        //返回结果
        return AjaxResult.success(page);
    }




}
